﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WP7Client.Controller;
using WP7Client.Helpers;
using WP7Client.Classes;

namespace WP7Client.UserInterface.Pages
{
    public partial class ChatPage : MSHPhoneApplicationPage
    {
        public ChatPage()
        {
            InitializeComponent();
        }

        private void MSHPhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = ControllerHelper.ChatController;
            ControllerHelper.ChatController.ChatPage = this;

            if (ControllerHelper.OverviewController.GotNewUnreadMessages)
                ControllerHelper.OverviewController.OverviewPage.TextBlockNewMessages.Visibility = Visibility.Visible;
            else
                ControllerHelper.OverviewController.OverviewPage.TextBlockNewMessages.Visibility = Visibility.Collapsed;
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);

            Conversation c = ControllerHelper.ChatController.Conversation;
            ControllerHelper.ChatController.Conversation = c;

            if (ControllerHelper.OverviewController.GotNewUnreadMessages)
                ControllerHelper.OverviewController.OverviewPage.TextBlockNewMessages.Visibility = Visibility.Visible;
            else
                ControllerHelper.OverviewController.OverviewPage.TextBlockNewMessages.Visibility = Visibility.Collapsed;
        }

        public void RefreshMessagesList()
        {
            ListBoxMessages.UpdateLayout();
            ListBoxMessages.ScrollIntoView(ListBoxMessages.Items.Last());
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if(!String.IsNullOrEmpty(TextBoxMessage.Text))
            {
                ControllerHelper.ChatController.AddMessage(TextBoxMessage.Text);
                TextBoxMessage.Text = "";
                RefreshMessagesList();
            }
        }
    }
}